package com.yanhao.aop.buriedpoint;

import android.util.Log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.annotation.Annotation;

/**
 * 埋点事件
 */

@Aspect
public class BuriedPointAspectJ {

    private static final String TAG = "BuriedPoint_TAG";

    @Around("execution(@com.yanhao.aop.buriedpoint.BuriedPoint * *(..))")
    public void buriedPointProcee(ProceedingJoinPoint joinPoint) throws JSONException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取对应方法上的注解
        BuriedPoint buriedPoint = signature.getMethod().getAnnotation(BuriedPoint.class);
        //获取注解中的参数值
        String eventID = buriedPoint.eventID();
        String eventName = buriedPoint.eventName();

        JSONObject params = new JSONObject();
        params.put("eventId", eventID);
        params.put("eventName", eventName);

        // 获取方法参数的注解
        Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();

        if (parameterAnnotations.length != 0) {
            int i = 0;
            for (Annotation[] parameterAnnotation : parameterAnnotations) {
                for (Annotation annotation : parameterAnnotation) {
                    if (annotation instanceof BuriedParameter) {
                        // 获取key value
                        String key = ((BuriedParameter) annotation).value();
                        Log.e(TAG, "key= " + key);
                        params.put(key, joinPoint.getArgs()[i++]);
                    }
                }
            }
        }

        // 上报
        Log.e(TAG, "上报数据---->" + params.toString());

        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }


    }

}
